<?php

namespace app\admin\controller\shopro;

use app\admin\model\shopro\Bonus;
use think\Db;
use think\exception\HttpResponseException;
use addons\shopro\exception\ShoproException;
use app\admin\model\shopro\Withdraw as WithdrawModel;
use app\admin\model\shopro\WithdrawLog as WithdrawLogModel;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\Admin as AdminModel;
use addons\shopro\service\Withdraw as WithdrawLibrary;
use addons\shopro\library\Operator;

/**
 * 提现
 */
class Withdraw extends Common
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new WithdrawModel;
        $this->logModel = new WithdrawLogModel;
    }



    /**
     * 提现列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            return $this->view->fetch();
        }

        $withdraws = $this->model->sheepFilter()->with(['user'])->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $withdraws);
    }


    /**
     * 提现日志
     */
    public function log($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $logs = $this->logModel->where('withdraw_id', $id)->order('id desc')->select();
        $morphs = [
            'user' => UserModel::class,
            'admin' => AdminModel::class,
            'system' => AdminModel::class
        ];
        $logs = morph_to($logs, $morphs, ['oper_type', 'oper_id']);
        $logs = $logs->toArray();

        // 解析操作人信息
        foreach ($logs as &$log) {
            $log['oper'] = Operator::info($log['oper_type'], $log['oper'] ?? null);
        }
        $this->success('获取成功', null, $logs);
    }


    public function handle($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->param();
        $action = $params['action'] ?? null;
        $refuse_msg = $params['refuse_msg'] ?? '';
        if ($action == 'refuse' && !$refuse_msg) {
            $this->error('请输入拒绝原因');
        }

        $ids = is_array($id) ? $id : explode(',', $id);
        foreach ($ids as $key => $id) {
            Db::startTrans();
            try {
                $withdraw = $this->model->lock(true)->where('id', $id)->find();
                if (!$withdraw) {
                    $this->error(__('No Results were found'));
                }
                $withdrawLib = new WithdrawLibrary($withdraw->user_id);

                switch ($action) {
                    case 'agree':
                        $withdraw = $withdrawLib->handleAgree($withdraw);
                        break;
                    case 'agree&withdraw':
                        $withdraw = $withdrawLib->handleAgree($withdraw);
                        $withdraw = $withdrawLib->handleWithdraw($withdraw);
                        break;
                    case 'withdraw':
                        $withdraw = $withdrawLib->handleWithdraw($withdraw);
                        break;
                    case 'refuse':
                        $withdraw = $withdrawLib->handleRefuse($withdraw, $refuse_msg);
                        break;
                }

                Db::commit();
            } catch (ShoproException $e) {
                Db::commit();       // 不回滚，记录错误日志
                $this->error($e->getMessage());
            } catch (HttpResponseException $e) {
                $data = $e->getResponse()->getData();
                $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                $this->error($message);
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->success('处理成功');
    }
    /**
     * 导出
     * */
    /*public function export()
    {
        $cellTitles = [
            'id' => 'ID',
            'user.id' => '用户ID',
            'user.nickname' => '用户昵称',
            'user.mobile' => '用户手机号码',
            'amount' => '实际到账/提现金额',
            'charge_fee' => '费率/手续费',
            'withdraw_type' => '提现方式',
            'withdraw_info' => '打款信息',
            'createtime' => '申请时间',
            'updatetime' => '上次操作时间',
            'status_text' => '状态',
        ];

        // 数据总条数
        $total = $this->model->sheepFilter()->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }
        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '提现明细列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
        ];
        $type=$this->model->withdrawTypeList();
        $result = $export->export($params, function ($pages) use ($total,$type) {
            $datas = $this->model->sheepFilter()->with(['user'])
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $datas = collection($datas);
            $newDatas = [];
            foreach ($datas as &$item) {
                $data = [
                    // 订单表字段
                    'id' => $item['id'],
                    'user.id' =>$item["user"]["id"]??0,
                    'user.nickname' =>$item["user"]["nickname"]??'',
                    'user.mobile' =>$item["user"]["mobile"]??'',
                    'amount' =>$item["paid_fee"]."/".$item["amount"],
                    'charge_fee' =>$item["charge_rate_format"]."/".$item["charge_fee"],
                    'withdraw_type' =>$type[$item["withdraw_type"]]??'银行卡',
                    'withdraw_info' =>"开户行:".$item["withdraw_info"]["开户行"]."\n".
                        "真实姓名:".$item["withdraw_info"]["真实姓名"]."\n".
                        "银行卡号:".$item["withdraw_info"]["银行卡号"],
                    'createtime' =>$item["createtime"],
                    'updatetime' =>$item["updatetime"],
                    'status_text' =>$item["status_text"],
                ];
                $newDatas[] = $data;
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }*/
    public function export()
    {
        $cellTitles = [
            'id' => 'ID',
            'user.id' => '会员编号',
            'bank_number' => '收款账号',
            'user.realname' => '收款户名',
            'user.idcard' => '身份证',
            'user.mobile' => '联系电话',
            'receipt' => '基础服务费金额',
            'money' => '提款金额（元）',
            'charge_fee' => '手续费（元）',
            'bank' => '提款银行',
            'createtime' => '提款申请时间',
            'status_text' => '状态',
            'type' => '提现类型',
        ];

        // 数据总条数
        $total = $this->model->sheepFilter()->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }
        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '提现明细列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
        ];
        $result = $export->export($params, function ($pages) use ($total) {
            $datas = $this->model->sheepFilter()->with(['user'])
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $datas = collection($datas);
            $newDatas = [];
            foreach ($datas as &$item) {
                $data = [
                    // 订单表字段
                    'id' => $item['id'],
                    'user.id' =>$item["user"]["id"]??0,
                    'bank_number' => "@".$item["withdraw_info"]["银行卡号"],
                    'user.realname' =>$item["withdraw_info"]["真实姓名"]??'',
                    'user.idcard' =>"@".$item["user"]["ID_number"]??'',
                    'user.mobile' =>"@".$item["user"]["mobile"]??'',
                    'receipt' =>$item["amount"],
                    'money' =>bcadd($item["amount"],$item["charge_fee"],2),
                    'charge_fee' =>$item["charge_fee"],
                    'bank' =>$item["withdraw_info"]["开户行"],
                    'createtime' =>$item["createtime"],
                    'status_text' =>$item["status_text"],
                    'type' => '',
                ];
                $newDatas[] = $data;
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
